using System;
using Castle.Core.Interceptor;
using log4net;

namespace Project.Library.Core.AOP
{
    /// <summary>
    /// Add basic logging functionality
    /// </summary>
    public class LogInterceptor : IInterceptor
    {
        #region IInterceptor Members

        public void Intercept(IInvocation invocation)
        {
            var logger = LogManager.GetLogger(invocation.TargetType);

            try
            {
                var methodName = "";

                // Show the called method name and arguments
                if (logger.IsDebugEnabled)
                {
                    methodName = InterceptorHelper.GetMethodName(invocation);
                    logger.Debug(methodName);
                }

                // Calling the method
                invocation.Proceed();

                // Show the result of the method
                if(logger.IsDebugEnabled)
                    logger.Debug(String.Format("Result of {0} is : {1}",methodName,invocation.ReturnValue));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }
        
        #endregion
    }
}